package com.ls.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ls.annotation.LoginRequired;
import com.ls.entity.Message;
import com.ls.entity.Page;
import com.ls.entity.User;
import com.ls.service.MessageService;
import com.ls.service.UserService;
import com.ls.util.CommunityConstant;
import com.ls.util.CommunityUtil;
import com.ls.util.UserContextHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.HtmlUtils;

import java.util.*;

/**
 * @author ls
 * @date 2020/12/30
 **/
@Controller
public class MessageController implements CommunityConstant {

    @Autowired
    private MessageService messageService;

    @Autowired
    private UserContextHolder userContextHolder;

    @Autowired
    private UserService userService;

    /**
     * 私信列表
     *
     * @param model
     * @param page
     * @return
     */
    @GetMapping("/letter/list")
    public String getLetterList(Model model, Page page) {
        User user = userContextHolder.getUser();
        // 设置分页信息
        page.setPath("/letter/list");
        page.setPageSize(5);
        // 设置总会话数
        page.setTotalCount(messageService.queryConversationCount(user.getId()));

        List<Message> conversations = messageService.queryConversations(user.getId(),
                page.getStartIndex(), page.getPageSize());

        List<Map<String, Object>> conversationVos = new ArrayList<>();
        conversations.forEach(conversation -> {
            Map<String, Object> conversationVo = new HashMap<>();
            conversationVo.put("conversation", conversation);
            conversationVo.put("letterCount",
                    messageService.queryLetterCount(conversation.getConversationId()));
            conversationVo.put("unreadCount",
                    messageService.queryLetterUnreadCount(user.getId(), conversation.getConversationId()));
            int targetId = user.getId() == conversation.getFromId() ? conversation.getToId() : conversation.getFromId();
            conversationVo.put("target", userService.queryUserById(targetId));
            conversationVos.add(conversationVo);
        });

        model.addAttribute("conversationVos", conversationVos);
        // 查询未读消息数量
        int letterUnreadCount = messageService.queryLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.queryNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "site/letter";
    }

    /**
     * 获取私信详情列表
     *
     * @param conversationId
     * @param model
     * @param page
     * @return
     */
    @GetMapping("/letter/detail/{conversationId}")
    public String getLetterDetail(@PathVariable("conversationId") String conversationId, Model model, Page page) {
        // 分页信息
        page.setPageSize(5);
        page.setPath("/letter/detail/" + conversationId);
        page.setTotalCount(messageService.queryLetterCount(conversationId));

        // 私信列表
        List<Message> letters = messageService.queryLetters(conversationId, page.getStartIndex(), page.getPageSize());
        List<Map<String, Object>> letterVos = new ArrayList<>();
        letters.forEach(letter -> {
            Map<String, Object> letterVo = new HashMap<>();
            letterVo.put("letter", letter);
            letterVo.put("fromUser", userService.queryUserById(letter.getFromId()));
            letterVos.add(letterVo);
        });

        model.addAttribute("letterVos", letterVos);

        // 私信目标
        model.addAttribute("target", getLetterTarget(conversationId));

        // 设置已读
        List<Integer> ids = getLetterIds(letters);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "site/letter-detail";
    }

    /**
     * 获取私信目标
     *
     * @param conversationId
     * @return
     */
    private User getLetterTarget(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);

        if (userContextHolder.getUser().getId() == id0) {
            return userService.queryUserById(id1);
        } else {
            return userService.queryUserById(id0);
        }
    }

    /**
     * 获取未读私信id
     *
     * @param letterList
     * @return
     */
    private List<Integer> getLetterIds(List<Message> letterList) {
        List<Integer> ids = new ArrayList<>();
        if (letterList != null) {
            for (Message message : letterList) {
                // 消息接收者是当前用户,且状态为未读
                if (userContextHolder.getUser().getId() == message.getToId()
                        && message.getStatus() == 0) {
                    ids.add(message.getId());
                }
            }
        }
        return ids;
    }


    /**
     * 发送私信
     *
     * @param username
     * @param content
     * @return
     */
    @PostMapping("/letter/send")
    @ResponseBody
    public String sendLetter(String username, String content) {
        User target = userService.queryUserByUsername(username);
        if (target == null) {
            return CommunityUtil.getJSONString(1, "目标用户不存在");
        }

        // 设置消息
        Message message = new Message();
        message.setFromId(userContextHolder.getUser().getId());
        message.setToId(target.getId());
        message.setContent(content);
        message.setCreateTime(new Date());
        if (message.getFromId() < message.getToId()) {
            message.setConversationId(message.getFromId() + "_" + message.getToId());
        } else {
            message.setConversationId(message.getToId() + "_" + message.getFromId());
        }

        messageService.addMessage(message);

        return CommunityUtil.getJSONString(200);
    }

    /**
     * 通知列表
     *
     * @param model
     * @return
     */
    @LoginRequired
    @GetMapping("/notice/list")
    public String getNoticeList(Model model) {
        User user = userContextHolder.getUser();

        // 查询评论类通知
        Message message = messageService.queryLatestNotice(user.getId(), TOPIC_COMMENT);
        Map<String, Object> messageVo = new HashMap<>();
        if (message != null) {

            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
            });

            messageVo.put("user", userService.queryUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("postId", data.get("postId"));

            int count = messageService.queryNoticeCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("count", count);

            int unread = messageService.queryNoticeUnreadCount(user.getId(), TOPIC_COMMENT);
            messageVo.put("unread", unread);
        }
        model.addAttribute("commentNotice", messageVo);

        // 查询点赞类通知
        message = messageService.queryLatestNotice(user.getId(), TOPIC_LIKE);
        messageVo = new HashMap<>();
        if (message != null) {
            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
            });

            messageVo.put("user", userService.queryUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));
            messageVo.put("postId", data.get("postId"));

            int count = messageService.queryNoticeCount(user.getId(), TOPIC_LIKE);
            messageVo.put("count", count);

            int unread = messageService.queryNoticeUnreadCount(user.getId(), TOPIC_LIKE);
            messageVo.put("unread", unread);
        }
        model.addAttribute("likeNotice", messageVo);

        // 查询关注类通知
        message = messageService.queryLatestNotice(user.getId(), TOPIC_FOLLOW);
        messageVo = new HashMap<>();
        if (message != null) {
            messageVo.put("message", message);

            String content = HtmlUtils.htmlUnescape(message.getContent());
            Map<String, Object> data = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
            });

            messageVo.put("user", userService.queryUserById((Integer) data.get("userId")));
            messageVo.put("entityType", data.get("entityType"));
            messageVo.put("entityId", data.get("entityId"));

            int count = messageService.queryNoticeCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("count", count);

            int unread = messageService.queryNoticeUnreadCount(user.getId(), TOPIC_FOLLOW);
            messageVo.put("unread", unread);
        }
        model.addAttribute("followNotice", messageVo);

        // 查询未读消息数量
        int letterUnreadCount = messageService.queryLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        int noticeUnreadCount = messageService.queryNoticeUnreadCount(user.getId(), null);
        model.addAttribute("noticeUnreadCount", noticeUnreadCount);

        return "site/notice";
    }

    @LoginRequired
    @GetMapping("/notice/detail/{topic}")
    public String getNoticeDetail(@PathVariable("topic") String topic, Page page, Model model) {
        User user = userContextHolder.getUser();

        page.setPageSize(5);
        page.setPath("/notice/detail/" + topic);
        page.setTotalCount(messageService.queryNoticeCount(user.getId(), topic));

        List<Message> noticeList = messageService.queryNotices(user.getId(), topic, page.getStartIndex(), page.getPageSize());
        List<Map<String, Object>> noticeVOList = new ArrayList<>();
        if (noticeList != null) {
            for (Message notice : noticeList) {
                Map<String, Object> noticeVO = new HashMap<>();
                // 通知
                noticeVO.put("notice", notice);
                // 内容
                String content = HtmlUtils.htmlUnescape(notice.getContent());
                Map<String, Object> data = JSON.parseObject(content, new TypeReference<HashMap<String, Object>>() {
                });
                noticeVO.put("user", userService.queryUserById((Integer) data.get("userId")));
                noticeVO.put("entityType", data.get("entityType"));
                noticeVO.put("entityId", data.get("entityId"));
                noticeVO.put("postId", data.get("postId"));
                // 通知作者
                noticeVO.put("fromUser", userService.queryUserById(notice.getFromId()));

                noticeVOList.add(noticeVO);
            }
        }
        model.addAttribute("noticeVOList", noticeVOList);

        // 设置已读
        List<Integer> ids = getLetterIds(noticeList);
        if (!ids.isEmpty()) {
            messageService.readMessage(ids);
        }

        return "site/notice-detail";
    }

}
